package io.xxx.mario.config;

import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.GenericApplicationContext;

@Configuration
public class RateLimiterManager {

    private final DefaultListableBeanFactory beanFactory;
    private final RedissonClient client;

    public RateLimiterManager(ApplicationContext applicationContext, RedissonClient client) {
        GenericApplicationContext context = (GenericApplicationContext) applicationContext;
        this.beanFactory = (DefaultListableBeanFactory) context.getBeanFactory();
        this.client = client;
    }

    public void add(Long robotId) {
        RRateLimiter rateLimiter = client.getRateLimiter(getKey(robotId));
        rateLimiter.setRate(RateType.OVERALL, 1, 1, RateIntervalUnit.SECONDS);
        beanFactory.registerSingleton(String.valueOf(robotId), rateLimiter);
    }

    public void remove(String name) {
        beanFactory.destroySingleton(name);
    }

    public RRateLimiter get(Long robotId) {
        return beanFactory.getBean(getKey(robotId), RRateLimiter.class);
    }

    private String getKey(Long robotId) {
        return "robot:" + robotId;
    }

}
